<?php

use console\db\Migration;
use common\models\rbac\Menu;
use common\models\rbac\Route;
use common\helpers\ArrayHelper;
use mdm\admin\components\Configs;

/**
 * 初始化基础菜单
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m200104_091353_d_auth_menu extends Migration {

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $model = new Route();
        $model->invalidate();
        $routes = $model->getRoutes();
        $assigned = $routes['assigned'];

        $saved = ArrayHelper::map(Menu::findAll(['route' => array_values($assigned)]), 'route', 'route');
        if (!empty($saved)) {
            $assigned = ArrayHelper::diffrent($assigned, $saved);
        }

        foreach ($assigned as $r) {
            $menu = Menu::findOne(['route' => $r]);
            if ($menu == null) {
                $menu = new Menu();
                $menu->attributes = ['name' => str_replace('/', '.', trim($r, '/')), 'route' => $r];
            }
            if (str_replace($model->filterWords, '', $r) !== $r) {
                $menu->visibled = 0;
            }
            if (!$menu->save()) {
                return false;
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->truncateTable(Configs::instance()->menuTable);
    }

}
